package day0307;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class Demo06 {

    public static void main(String[] args) {
        Comparator comparator = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Person p1 && o2 instanceof Person p2){
                    return p1.getAge() - p2.getAge();
                }
                return 0;
            }
        };

        Comparator cpr = (o1, o2) -> {
            if (o1 instanceof Person p1 && o2 instanceof Person p2){
                return p1.getAge() - p2.getAge();
            }
            return 0;
        };

        // 所有的元素是可比较的，或是由比较器进行比较
        Set set = new TreeSet(cpr);

        // 实现 Comparable
//        set.add(new Student("张三",18));
//        set.add(new Student("张三",18));
//        set.add(new Student("张三",18));
//        set.add(new Student("张三",18));
//        set.add(null); exception

        set.add(new Person("张三", 18));
        set.add(new Person("张三", 19));
        set.add(new Person("张三", 18));

        System.out.println(set);
    }
}

class Person {
    private String name;

    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

class PersonComparator implements Comparator {

    @Override
    public int compare(Object o1, Object o2) {
        if (o1 instanceof Person p1 && o2 instanceof Person p2){
            return p1.getAge() - p2.getAge();
        }
        return 0;
    }
}


